package models

import (
	"errors"
	"fmt"
	"math"
	"reflect"
	"strconv"
	"strings"

	"time"

	"github.com/astaxie/beego/orm"
)

type SaleOrder struct {
	Id       int     `orm:"column(id);auto"`                       //
	Name     string  `orm:"column(name);size(255)"`                //标题
	Uid      int     `orm:"column(uid)"`                           //用户ID
	Onum     string  `orm:"column(onum);size(255)"`                //订单编号
	Partner  int     `orm:"column(partner)"`                       //客户
	State    int     `orm:"column(state)"`                         //订单状态  0 未付款  1已付款
	Province int     `orm:"column(province)"`                      //省
	City     int     `orm:"column(city)"`                          //市
	District int     `orm:"column(district)"`                      //县/区
	Zprice   float64 `orm:"column(zprice);digits(10);decimals(2)"` //总价
	Street   string  `orm:"column(street);size(255)"`              //详细地址
	Ctime    int64   `orm:"column(ctime)"`                         //订单生成时间

	Goods    []string `orm:"-"` //商品ID
	GoodsNum []string `orm:"-"` //数量
}

type SaleOrders struct {
	Id       int     `orm:"column(id);auto"`                       //
	Name     string  `orm:"column(name);size(255)"`                //标题
	Uid      int     `orm:"column(uid)"`                           //用户ID
	Onum     string  `orm:"column(onum);size(255)"`                //订单编号
	Partner  int     `orm:"column(partner)"`                       //客户
	State    int     `orm:"column(state)"`                         //订单状态  0 未付款  1已付款
	Province int     `orm:"column(province)"`                      //省
	City     int     `orm:"column(city)"`                          //市
	District int     `orm:"column(district)"`                      //县/区
	Zprice   float64 `orm:"column(zprice);digits(10);decimals(2)"` //总价
	Street   string  `orm:"column(street);size(255)"`              //详细地址
	Ctime    int64   `orm:"column(ctime)"`                         //订单生成时间
	Cname    string  `orm:"column(cname);size(255)"`               //采购商姓名
}

func (t *SaleOrder) TableName() string {
	return "my_sale_order"
}

func init() {
	orm.RegisterModel(new(SaleOrder))
}

// AddSaleOrder insert a new SaleOrder into database and returns
// last inserted Id on success.
func AddSaleOrder(m *SaleOrder) (id int64, err error) {
	o := orm.NewOrm()
	id, err = o.Insert(m)
	if err != nil {
		return
	}
	//循环写入 订单商品表

	for k, v := range m.Goods {
		var md OrderGoods
		md.Oid = int(id)
		i, _ := strconv.Atoi(v)
		md.Gid = i
		n, _ := strconv.Atoi(m.GoodsNum[k])
		md.Num = n
		md.Ctime = int(time.Now().Unix())
		AddOrderGoods(&md)
	}

	return
}

//修改销售订单  一般是可以改地址 状态 等部分字段
func UpdatSaleByID(m *SaleOrder) (err error) {
	o := orm.NewOrm()
	_, err = o.QueryTable(new(SaleOrder)).Filter("Id", m.Id).Update(orm.Params{
		"Name":     m.Name,
		"State":    m.State,
		"Street":   m.Street,
		"Province": m.Province,
		"City":     m.City,
		"District": m.District,
	})
	return
}

func GetSaleOrderList(page int64, page_size int64, where string) (count int64, l []SaleOrders) {
	o := orm.NewOrm()
	var err error
	qbs, _ := orm.NewQueryBuilder("mysql")
	qbs = qbs.Select("count(*) as count").From("my_sale_order")
	if where != "" {
		qbs = qbs.Where(where)
	}
	sqls := qbs.String()
	err = o.Raw(sqls).QueryRow(&count)
	if err != nil {
		return
	}
	var offset int64
	if page <= 1 {
		offset = 0
	} else {
		offset = (page - 1) * page_size
	}
	if page*page_size > count {
		if page_size > count {
			offset = 0
		} else {
			s := math.Floor(float64(count)/float64(page_size)) * float64(page_size)
			offset = int64(s)
		}
	}

	qb, _ := orm.NewQueryBuilder("mysql")
	qb = qb.Select("my_sale_order.*", "my_clients.name as cname").From("my_sale_order").
		LeftJoin("my_clients").On("my_sale_order.partner=my_clients.id")
	if where != "" {
		qb = qb.Where(where)
	}
	qb = qb.Limit(int(page_size)).Offset(int(offset))
	sql := qb.String()
	_, err = o.Raw(sql).QueryRows(&l)
	fmt.Println(err)
	return
}

// GetSaleOrderById retrieves SaleOrder by Id. Returns error if
// Id doesn't exist
func GetSaleOrderById(id int) (v *SaleOrder, err error) {
	o := orm.NewOrm()
	v = &SaleOrder{Id: id}
	if err = o.Read(v); err == nil {
		return v, nil
	}
	return nil, err
}

// GetAllSaleOrder retrieves all SaleOrder matches certain condition. Returns empty list if
// no records exist
func GetAllSaleOrder(query map[string]string, fields []string, sortby []string, order []string,
	offset int64, limit int64) (ml []interface{}, err error) {
	o := orm.NewOrm()
	qs := o.QueryTable(new(SaleOrder))
	// query k=v
	for k, v := range query {
		// rewrite dot-notation to Object__Attribute
		k = strings.Replace(k, ".", "__", -1)
		if strings.Contains(k, "isnull") {
			qs = qs.Filter(k, (v == "true" || v == "1"))
		} else {
			qs = qs.Filter(k, v)
		}
	}
	// order by:
	var sortFields []string
	if len(sortby) != 0 {
		if len(sortby) == len(order) {
			// 1) for each sort field, there is an associated order
			for i, v := range sortby {
				orderby := ""
				if order[i] == "desc" {
					orderby = "-" + v
				} else if order[i] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
			qs = qs.OrderBy(sortFields...)
		} else if len(sortby) != len(order) && len(order) == 1 {
			// 2) there is exactly one order, all the sorted fields will be sorted by this order
			for _, v := range sortby {
				orderby := ""
				if order[0] == "desc" {
					orderby = "-" + v
				} else if order[0] == "asc" {
					orderby = v
				} else {
					return nil, errors.New("Error: Invalid order. Must be either [asc|desc]")
				}
				sortFields = append(sortFields, orderby)
			}
		} else if len(sortby) != len(order) && len(order) != 1 {
			return nil, errors.New("Error: 'sortby', 'order' sizes mismatch or 'order' size is not 1")
		}
	} else {
		if len(order) != 0 {
			return nil, errors.New("Error: unused 'order' fields")
		}
	}

	var l []SaleOrder
	qs = qs.OrderBy(sortFields...)
	if _, err = qs.Limit(limit, offset).All(&l, fields...); err == nil {
		if len(fields) == 0 {
			for _, v := range l {
				ml = append(ml, v)
			}
		} else {
			// trim unused fields
			for _, v := range l {
				m := make(map[string]interface{})
				val := reflect.ValueOf(v)
				for _, fname := range fields {
					m[fname] = val.FieldByName(fname).Interface()
				}
				ml = append(ml, m)
			}
		}
		return ml, nil
	}
	return nil, err
}

// UpdateSaleOrder updates SaleOrder by Id and returns error if
// the record to be updated doesn't exist
func UpdateSaleOrderById(m *SaleOrder) (err error) {
	o := orm.NewOrm()
	v := SaleOrder{Id: m.Id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Update(m); err == nil {
			fmt.Println("Number of records updated in database:", num)
		}
	}
	return
}

// DeleteSaleOrder deletes SaleOrder by Id and returns error if
// the record to be deleted doesn't exist
func DeleteSaleOrder(id int) (err error) {
	o := orm.NewOrm()
	v := SaleOrder{Id: id}
	// ascertain id exists in the database
	if err = o.Read(&v); err == nil {
		var num int64
		if num, err = o.Delete(&SaleOrder{Id: id}); err == nil {
			fmt.Println("Number of records deleted in database:", num)
		}
	}
	return
}
